package AgentsDB;

import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import searchEngine.*;

public class AgentUtils {
	public static boolean isAgent(String agentPhoneNumber, String agentObjectDataFilePath){
		try{
			FileInputStream inputStream = new  FileInputStream(agentObjectDataFilePath);
			ObjectInputStream objectinputStream = new ObjectInputStream(inputStream);
			@SuppressWarnings("unchecked")
			Set<Agent> agents = (Set<Agent>) objectinputStream.readObject();
			Agent agent = new Agent("test",new Long(agentPhoneNumber));
			return agents.contains(agent);
		}catch(IOException e){
			e.printStackTrace(System.out);
			return false;
		} catch (ClassNotFoundException e) {
			e.printStackTrace(System.out);
			return false;
		}
		
	}
	/**
     * Make search in each url from urllist.
     * AgentMessageExpr should match message only with agent information.
     * No agent phone names should be there.
     */
	public static Set<Agent> searchAgents(List<URL> urlList, String agentMessageExpr, String agentNameExpr, String agentPhoneExpr){

		System.out.println("Found adv urls number: " + urlList.size());
		System.out.println("Sarching for agents");
		System.out.println("[--------------------]100%");
		System.out.print("[");
		
		int group = urlList.size()/20;
		int i =0;
		Date date = new Date();
		Iterator<URL> iterator = urlList.iterator();
		Set<Agent> agents= new HashSet<Agent>();
		while(iterator.hasNext()){
			try {
				URL url = iterator.next();
				StringBuilder temp = SearchEngine.search(agentMessageExpr,url, System.getProperty("line.separator"));	
				System.out.println("<a href="+url+">...</><br/>");
				if(temp.length()>1){
					//System.out.println(temp);
					Matcher agentNamePattern = Pattern.compile(agentNameExpr).matcher(temp.toString());
					agentNamePattern.find();
					String agentName = agentNamePattern.group();
					Matcher agentPhonePattern = Pattern.compile(agentPhoneExpr)
							.matcher(temp.toString());
					while (agentPhonePattern.find()) {
						// agentPhonePattern.group();
						Long phoneNumber = new Long(agentPhonePattern.group().replaceAll("[^\\d]*", ""));
						Agent agent = new Agent(phoneNumber,agentName,date,url.getHost());
						agents.add(agent);
						System.out.println(agent.getAgentName()+" "+agent.getPhoneNumber());	
					}

			}
			i+=1;
			if ((i % group)==0)System.out.print("|");
			} catch (Exception e) {
				// Logger should be applied
				System.out.print("e"+i);
			}
		}
		System.out.println("]100%");
		return agents;
	}
}

